// PermissionsService.cs
// Facebook/Framework/Service
// Copyright (c) 2007, Nikhil Kothari. All Rights Reserved.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Facebook.Service.Core;

namespace Facebook.Service {

    /// <summary>
    /// Represents the service APIs that allow determining whether specific permissions
    /// have been granted to the application.
    /// </summary>
    public sealed class PermissionsService {

        private FacebookSession _session;

        internal PermissionsService(FacebookSession session) {
            Debug.Assert(session != null);
            _session = session;
        }

        /// <summary>
        /// Determines if the user has granted a specific permission.
        /// </summary>
        /// <param name="permission">The permission being tested for.</param>
        /// <returns>true if the permission has been granted; false otherwise.</returns>
		public bool IsPermissionGranted(Permission permission)
		{
			return IsPermissionGranted(_session.UserID, permission);
		}
		/// <summary>
		/// Determines if the user has granted a specific permission.
		/// </summary>
		/// <param name="userID">The user whose permissions are to be checked; null if it is the current user.</param>
		/// <param name="permission">The permission being tested for.</param>
		/// <returns>true if the permission has been granted; false otherwise.</returns>
		public bool IsPermissionGranted(string userID, Permission permission)
		{
			if (String.IsNullOrEmpty(userID))
			{
				userID = _session.UserID;
			}
			bool isDesktopApp = (_session.ApplicationType == FacebookApplicationType.Client);
            string permissionName = null;
            switch (permission) {
                case Permission.SetStatus:
                    permissionName = "status_update";
                    break;
				case Permission.EmailUser:
					permissionName = "email";
					break;
				case Permission.OfflineAccess:
					permissionName = "offline_access";
					break;
                case Permission.UploadPhoto:
                    permissionName = "photo_upload";
                    break;
                case Permission.CreateListing:
                    permissionName = "create_listing";
                    break;
            }

			// Session key is only required for desktop applications
            FacebookRequest request = new FacebookRequest(_session, isDesktopApp);
			if (!isDesktopApp)
			{
				request.Parameters["uid"] = userID;
			}
            request.Parameters["ext_perm"] = permissionName;

            FacebookResponse response = request.InvokeMethod("users.hasAppPermission");
            if (response.Status == FacebookResponseStatus.Succeeded) {
                return FacebookResponse.CoerceBoolean(response.Result);
            }

            return false;
        }
    }
}
